#begin:ifipy
try:
    get_ipython()
except:
    #begin: change to current dir
    from os import path,chdir,getcwd
    from sys import argv
    s1=path.dirname(argv[0]) 
    cwd=s1 if s1!="" else getcwd()
    chdir(cwd)
    del s1
    #end: change to current dir
#end:ifipy

#本想获取压缩包 但还是获取目录方便 不用检查 不用建立临时目录
def get_zip(dl):
    root = Tk().withdraw()
    save_folder = tkinter.filedialog.askdirectory(title=dl);
    print(save_folder)
    return save_folder
import os;# .path.join(), .listdir(), .chdir(), .getcwd() 등 사용

#com interface
import win32com.client as win32
#import win32gui  # 창 숨기기 위한 모듈
try:wrd = win32.gencache.EnsureDispatch('kwps.Application') 
except:wrd = win32.gencache.EnsureDispatch('Word.Application') 
wrd.Visible = False  #需调试时则设为True
wdFormatDocumentDefault =    16 

import atexit; #退出打开的word/wps窗口
def wrdQuit(): wrd.Quit();
atexit.register(wrdQuit)

from tkinter import *
import tkinter.filedialog
import re;

#maybe get from argv[1] faster
docdir=get_zip("选择裁判文书网已下载doc文件的目录(部分文档需word2010更高版本，或wps才能打开)");
il=[path.join(docdir,i) for i in os.listdir(docdir) if re.match(r".*\.doc$",i,flags=re.I) is not None]
for f in il:
    err=0;
    with open(f,"rb") as i:
        a=i.read()
    b=a.find(b"<html>")
    a=a[b:]
    b=a.find(b"</html>")
    a=a[:b+len("</html>")];
    tmp=a;
    try:
        a=re.sub(rb'(charset=)("?)(utf-8)(")',rb'\1\2gb18030\3',a,flags=re.I);
        aa=a.decode("gb18030");
    except UnicodeDecodeError:
        try:
            a=re.sub(rb'(charset=)("?)(utf-8|gb18030)(")',rb'\1\2gbk\3',a,flags=re.I);
            aa=a.decode("gbk");
        except UnicodeDecodeError:
            a=tmp;
            #with open(f+".tmp","wb") as o: o.write(a);
            #调试文件保存
            err=1;
            wrdf = wrd.Documents.Open(f);
            wrdf.SaveAs(f+"x" , wdFormatDocumentDefault);
            wrdf.Close()
    if err!=1: 
        with open(f+"x.tmp","w") as o: o.write(aa);
        if 1:#手机qq、tim、手机qq浏览器查看 兼容
            wrdf = wrd.Documents.Open(f+"x.tmp");
            wrdf.SaveAs(f+"x" ,wdFormatDocumentDefault);
            wrdf.Close()
            os.remove(f+"x.tmp")

